package com.jasony.tools.excel;

import com.jasony.tools.excel.ExcelWorkBook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

public class ExcelOption {
    private Workbook workbook;
    private ExcelWorkBook excelWorkBook;

    private ExcelOption(Workbook workbook, ExcelWorkBook excelWorkBook) {
        this.excelWorkBook = excelWorkBook;
        this.workbook = workbook;
    }

    public static ExcelOption build(Workbook workbook, ExcelWorkBook excelWorkBook) {
        Objects.requireNonNull(workbook);
        return new ExcelOption(workbook, excelWorkBook);
    }

    public OutputStream toOutputStream() throws IOException {
        OutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        return os;
    }

    public OutputStream writeResponse(HttpServletResponse response) throws IOException {
        responseHeader(response);
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        return out;
    }

    private void responseHeader(HttpServletResponse response) {
        if (excelWorkBook != null) {
            try {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String(excelWorkBook.getFileName().getBytes("gb2312"), "ISO8859-1"));
            } catch (UnsupportedEncodingException e) {
                //Ignore
                e.printStackTrace();
            }
            response.setHeader("content-type", "application/excel");
        }
    }
}
